import {useAreaInfoStore} from '@/stores/area.js'
import { getGroupId } from '@/api/BussinessMenage/index.js'
const useAreaInfo = useAreaInfoStore()

/**
 * 选择地址方法
 * @param {Object} val 选择城市的areaCode example:  {0: '110000', 1: '110100', 2: '110111'} 北京市 / 北京城区 / 房山区
 * @param {*} list 所有城市对应编码
 * @param {*} form 绑定的表单
 * @returns 
 */
 export const handleAddsChange = async(val,list,form = {},obj = {},isDoor = false) => {

     form.addressName = []
     if(!val.length){ return}
    //  form.addressName
      

     let Obj = handleSelect(val,list,obj)
     console.log(Obj,'obj');
     form.addressName = Obj.address
     if(isDoor){
      let result
        try {
          let data = {
            provinceId:Obj.regionId[0],
            cityId:Obj.regionId[1],
            areaId:Obj.regionId[2],
          }
          result = await getGroupId(data)
       
      } catch (error) {
        
        }finally{
          form.storeGroupId = result?.permissionId || ''
        }
     }
  
   }

  export const handleSelect = (e, list, obj = {}) =>  {

     for (let i = 0; i < list.length; i++) {
      // console.log(list,'list');
       let { area_name, area_code, children, id } = list[i];
       let _find = e.includes(area_code);
       if (_find) {
         obj.address.push(area_name);
         obj.regionId.push(id);
         if (children && children.length) {
            handleSelect(e, children, obj);
         }
         break;
       }
     }
     return obj;
  }
 


export const getAreaInfo = () => {


    return useAreaInfo.AreaInfo
}


// 带权限的地区数据
export const getAreaRolesInfo = () => {
  return useAreaInfo.AreaRolesInfo
}

  
  /**
   * 防抖函数
   * @param {Function} fn 执行函数 
   * @param {Number} time 防抖时间
   * @returns 
   */
  export const debounce = (fn, time) => {
    let timer
    return function (...argu) {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
      timer = setTimeout(() => {
        fn(...argu)
        clearTimeout(timer)
        timer = null
      }, time)
    }
  }
  
  
